package router

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"prac3/handler"
	"prac3/pkg"
)

func Router() *gin.Engine {

	r := gin.Default()

	r.Use(Cors()) //默认跨域
	r.Static("/static", "./static")

	user := r.Group("/user")
	user.POST("/login", handler.Login)
	user.POST("/roleNodeAdd", handler.RoleNodeAdd)
	user.POST("/userRoleAdd", handler.UserRoleAdd)
	user.GET("/userRole", handler.UserRole)
	user.GET("/roleNode", handler.RoleNode)
	user.GET("/userList", handler.UserList)

	car := r.Group("/car")
	car.POST("/carAdd", handler.CarAdd)
	car.POST("/carOrderAdd", handler.CarOrderAdd)
	car.GET("/carOrderList", handler.CarOrderList)
	car.GET("/carOrderDetail", handler.CarOrderDetail)

	repo := r.Group("/repo")
	repo.POST("/repoAdd", handler.RepoAdd)
	repo.POST("/repoOrderAdd", handler.RepoOrderAdd)
	repo.GET("/repoOrderList", handler.RepoOrderList)
	repo.GET("/repoOrderDetail", handler.RepoOrderDetail)

	r.POST("/info", MiddleWare(), handler.Info)
	return r
}
func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("token")
		if tokenString == "" {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "不能空",
			})
			c.Abort()
		}
		getToken, err := pkg.GetToken(tokenString)
		if err != "" {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "解密失败",
			})
			c.Abort()
		}
		c.Set("uid", getToken["uid"])
		c.Next()
	}
}

func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
